package com.lhd.qd.config;

import com.lhd.qd.common.consts.CommonConsts;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.Collections;
import java.util.List;

/**
 * 接口文档配置
 */
@EnableSwagger2WebMvc
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createSystemApi() {
        return createDocket("1系统管理", "com.lhd.qd.module.system");
    }

    @Bean
    public Docket createRegistrationApi() {
        return createDocket("2其他模块", "com.lhd.qd.module.other");
    }

    private Docket createDocket(String groupName, String basePackage) {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .apiInfo(new ApiInfoBuilder().title("").build())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<ApiKey> securitySchemes() {
        return Collections.singletonList(
                new ApiKey(
                        CommonConsts.REQUEST_HEADER_TOKEN_KEY,
                        CommonConsts.REQUEST_HEADER_TOKEN_KEY,
                        "header")
        );
    }

    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(authorizationScope()).build()
        );
    }

    private List<SecurityReference> authorizationScope() {

        return Collections.singletonList(
                new SecurityReference(
                        CommonConsts.REQUEST_HEADER_TOKEN_KEY,
                        new AuthorizationScope[]{new AuthorizationScope("global", "")}
                        )
        );
    }

}
